<?php

namespace app\admin\logic\system;

use app\admin\model\model\system\SystemAccount;
use app\Request;

class LoginLogic
{
	// 保存到session中的用户信息的key
	const LOGIN_SESSION_KEY = 'login';

    // 验证码保存到session中的key
    const YZM_KEY = 'yzm';

    const TOKEN_ADMIN = 'token_admin';

    public static function loginByToken(Request $request) {
        // 获取cookie
        $tokenCookie = $request->cookie(self::TOKEN_ADMIN);
        if(!$tokenCookie) {
            return false;
        }

        // 有则进行判断
        $info = SystemAccount::getByToken($tokenCookie);
        if(!$info) {
            return false;
        }

        self::saveSession($info);

        // 修改登录时间
        SystemAccount::changeLastLogin($info->getId());

        // 返回
        return $tokenCookie;
    }

	public static function loginReturnToken($username, $password) {
        $user = SystemAccount::getByUsername($username);
        if(!$user) {
            \Debug::setDebug('账号密码错误');
            return false;
        }

        if(!password_verify($password, $user->getPassword())) {
            \Debug::setDebug('账号密码错误.');
            return false;
        }

        // 保存 session
		self::saveSession($user);

        // 返回token, 修改登录时间
        $token = $user->getToken();
        if(!$token) {
            $token = md5($username . time());
            SystemAccount::changeLastLogin($user->getId(), $token);
        } else {
            SystemAccount::changeLastLogin($user->getId());
        }

        return $token;
	}

    public static function saveYzm($val) {
        return session(self::YZM_KEY, $val);
    }

    public static function getYzm() {
        return session(self::YZM_KEY);
    }

    public static function check() {
        return session(self::LOGIN_SESSION_KEY);
    }

    // 验证密码
    public static function checkPassword($password, $hash) {
        return password_verify($password, $hash);
    }

    public static function logout() {
        SystemAccount::cleanToken(self::getId());
        return session(self::LOGIN_SESSION_KEY, null);
    }

	public static function saveSession($data) {
		session(self::LOGIN_SESSION_KEY, $data);
	}

	public static function getUsername() {
		return session(self::LOGIN_SESSION_KEY . '.username');
	}

    public static function getId() {
        return session(self::LOGIN_SESSION_KEY . '.id');
    }

    // 获取密码,加密后的
    public static function getPassword() {
        return session(self::LOGIN_SESSION_KEY . '.password');
    }
}